<template>
  <div class="exam-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试详情</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleEdit">编辑考试</el-button>
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>

      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="考试名称">{{ examData.title }}</el-descriptions-item>
        <el-descriptions-item label="考试状态">
          <el-tag :type="getStatusType(examData.status)">
            {{ getStatusText(examData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ examData.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ examData.endTime }}</el-descriptions-item>
        <el-descriptions-item label="考试时长">{{ examData.duration }}分钟</el-descriptions-item>
        <el-descriptions-item label="总分">{{ examData.totalPoints }}分</el-descriptions-item>
        <el-descriptions-item label="及格分数">{{ examData.passScore }}分</el-descriptions-item>
        <el-descriptions-item label="防作弊等级">
          <el-tag :type="getAntiCheatingType(examData.antiCheatingLevel)">
            {{ getAntiCheatingText(examData.antiCheatingLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="考试说明" :span="2">
          {{ examData.description }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 考试设置 -->
      <el-descriptions title="考试设置" :column="2" border class="mt-4">
        <el-descriptions-item label="允许重考">
          <el-tag :type="examData.allowRetake ? 'success' : 'info'">
            {{ examData.allowRetake ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="自动评分">
          <el-tag :type="examData.autoGrade ? 'success' : 'info'">
            {{ examData.autoGrade ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="显示答案">
          <el-tag :type="examData.showAnswer ? 'success' : 'info'">
            {{ examData.showAnswer ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="人脸验证">
          <el-tag :type="examData.faceVerification ? 'success' : 'info'">
            {{ examData.faceVerification ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 考试统计 -->
      <el-row :gutter="20" class="mt-4">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <span>总人数</span>
                <el-icon><User /></el-icon>
              </div>
            </template>
            <div class="stat-value">{{ statistics.totalStudents }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <span>已参加</span>
                <el-icon><Check /></el-icon>
              </div>
            </template>
            <div class="stat-value">{{ statistics.attendedStudents }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <span>及格率</span>
                <el-icon><DataLine /></el-icon>
              </div>
            </template>
            <div class="stat-value">{{ statistics.passRate }}%</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <template #header>
              <div class="stat-header">
                <span>平均分</span>
                <el-icon><TrendCharts /></el-icon>
              </div>
            </template>
            <div class="stat-value">{{ statistics.averageScore }}</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 作弊记录 -->
      <el-card class="mt-4">
        <template #header>
          <div class="card-header">
            <span>作弊记录</span>
            <el-button type="primary" link @click="handleViewAllEvents">
              查看全部
            </el-button>
          </div>
        </template>

        <el-table :data="cheatingEvents" border style="width: 100%">
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column prop="studentName" label="学生姓名" width="120" />
          <el-table-column prop="eventType" label="事件类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getEventTypeTag(row.eventType)">
                {{ getEventTypeText(row.eventType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="eventData" label="事件描述" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="handleViewEvidence(row)"
              >
                查看证据
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Check, DataLine, TrendCharts } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// Import API functions
import { getExamDetail, getCheatingEvents, getCheatingEvidence } from '@/api/exam'

const router = useRouter()
const route = useRoute()

// 考试数据
const examData = ref<any>({ // Use any for now based on mock data structure
  title: '',
  description: '',
  startTime: '',
  endTime: '',
  duration: 0,
  totalPoints: 0,
  passScore: 0,
  status: '',
  antiCheatingLevel: '',
  allowRetake: false,
  autoGrade: true,
  showAnswer: false,
  faceVerification: false
})

// 统计数据
const statistics = ref({
  totalStudents: 120,
  attendedStudents: 98,
  passRate: 85.5,
  averageScore: 78.6
})

// 作弊记录
const cheatingEvents = ref([
  {
    time: '2025-05-15 09:30:15',
    studentName: '张三',
    eventType: 'FACE_MISMATCH',
    eventData: '人脸识别不匹配，疑似替考'
  },
  {
    time: '2025-05-15 10:15:22',
    studentName: '李四',
    eventType: 'MULTI_FACE',
    eventData: '检测到多个面部，疑似多人参与'
  }
])

// 在 script setup 中添加以下代码
const currentEvidence = ref<any>(null)
const evidenceDialogVisible = ref(false)

// 获取状态类型
const getStatusType = (status: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const map: Record<number, string> = {
    0: '未开始',
    1: '进行中',
    2: '已结束'
  }
  return map[status] || '未知'
}

// 获取防作弊级别类型
const getAntiCheatingType = (level: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[level] || 'info'
}

// 获取防作弊级别文本
const getAntiCheatingText = (level: string) => {
  const map: Record<string, string> = {
    0: '无',
    1: '低',
    2: '中',
    3: '高'
  }
  return map[level] || '未知'
}

// 获取事件类型标签
const getEventTypeTag = (type: string) => {
  const map: Record<string, string> = {
    0: 'warning',
    1: 'danger',
    2: 'danger',
    3: 'warning'
  }
  return map[type] || 'info'
}

// 获取事件类型文本
const getEventTypeText = (type: string) => {
  const map: Record<string, string> = {
    0: '人脸不匹配',
    1: '多人参与',
    2: '屏幕共享',
    3: '复制粘贴'
  }
  return map[type] || '未知'
}

// 加载考试数据
const loadExamData = async () => {
  const examId = route.params.id
  try {
    // Replace axios call with API function call
    const response = await getExamDetail(Number(examId))
    const data = response.data
    // Update ref data correctly
    Object.assign(examData.value, data);

    // Load cheating events as well when exam data is loaded
    await loadCheatingEvents();

  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败')
  }
}

// 加载作弊事件
const loadCheatingEvents = async () => {
  const examId = route.params.id
  try {
    // Replace axios call with API function call
    const response = await getCheatingEvents(Number(examId))
    cheatingEvents.value = response.data // Assuming backend returns data in list field
  } catch (error) {
    console.error('获取作弊事件失败:', error)
    ElMessage.error('获取作弊事件失败')
  }
};

// 查看全部作弊事件（直接调用loadCheatingEvents）
const handleViewAllEvents = () => {
  loadCheatingEvents();
};

// 查看证据
const handleViewEvidence = async (row: any) => {
  const examId = route.params.id;
  const eventId = row.id; // Assuming the event object has an 'id' field
  try {
    // Replace axios call with API function call
    const response = await getCheatingEvidence(Number(examId), eventId);
    currentEvidence.value = response.data; // Assuming response.data contains the evidence
    evidenceDialogVisible.value = true;
  } catch (error) {
    console.error('获取作弊证据失败:', error);
    ElMessage.error('获取作弊证据失败');
  }
};

// 编辑考试
const handleEdit = () => {
  router.push(`/main/exam/edit/${route.params.id}`)
}

// 返回
const handleBack = () => {
  router.back()
}

// 页面加载时获取考试数据
onMounted(() => {
  loadExamData()
  // Initial load of cheating events handled in loadExamData
  // loadCheatingEvents();
})
</script>

<style scoped>
.exam-detail {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
}

:deep(.el-card) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.mt-4 {
  margin-top: 20px;
}

.stat-card {
  height: 100%;
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  margin-top: 10px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

:deep(.el-descriptions__body) {
  background-color: #fff;
}

:deep(.el-descriptions__label) {
  width: 120px;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-table .cell) {
  padding-left: 8px;
  padding-right: 8px;
}

:deep(.el-button--small) {
  padding: 4px 8px;
}
</style>
